<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="年级" prop="year">
        <el-select
          v-model="queryParams.year"
          clearable
          placeholder="请选择"
          size="small"
        >
          <el-option
            v-for="dict in dict.type.year_type"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
            size="small"
            @keyup.enter.native="handleQuery"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="班级名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入班级名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="年级" prop="year">
        <el-select v-model="queryParams.year"  clearable    placeholder="请选择年级" @change="getqueryFormclassList">
          <el-option
            v-for="dict in dict.type.year_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            @keyup.enter.native="handleQuery"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" :disabled='isClassDisabled' clearable   placeholder="请选择班级">
          <el-option
            v-for="item in classList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
            size="small"
            @keyup.enter.native="handleQuery">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="学校代码" prop="schoolCode">
        <el-input
          v-model="queryParams.schoolCode"
          placeholder="请输入学校代码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="studentList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="年级" align="center" prop="year">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.year_type" :value="scope.row.year" />
        </template>
      </el-table-column>
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-table
        v-loading="loading"
        :data="studentInfo"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="疫苗名称" align="center" prop="vaccinationName" />
        <el-table-column label="接种记录" align="center" prop="vaccinationDetail">
            <template slot-scope="scope">
                <el-checkbox v-for="(item, index) in scope.row.vaccinationDetail" :key="index" :value="item.status == '1'? true: false" disabled>{{ item.vacCount }}</el-checkbox>
            </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleInfo(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑疫苗详情 -->
    <el-dialog  :close-on-click-modal="false"
      title="编辑疫苗详情"
      :visible.sync="openInfo"
      width="400px"
      append-to-body
    >
    <el-form
      :model="infoParams"
      ref="infoForm"
      :inline="true"
      label-width="68px"
    >
    <el-form-item label="疫苗名称" prop="vaccinationName">
        <el-input
        disabled
          v-model="infoParams.vaccinationName"
          placeholder="请输入疫苗名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="接种记录" prop="vaccinationDetail">
        <el-checkbox-group v-model="infoParams.checkVaccinationDetail" >
            <el-checkbox @change="handleChecked(index)"  v-for="(item, index) in infoParams.vaccinationDetail" :key="index" :label="item.vacCount" :value="item.status == '1'? true:false"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormInfo">确 定</el-button>
        <el-button @click="openInfo = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

  <script>
import {
  listClazz,
  getClazz,
  delClazz,
  disableClazz,
  enableClazz,
  graduationClazz,
  addClazz,
  updateClazz,
  exportClazz,
  importTemplate,
} from "@/api/base/clazz";

import { vaccinationRecordList, batchUpdate } from "@/api/vaccineManagement/index";
import { listStudent } from "@/api/base/student";
import { listTeacher, selectTeacher } from "@/api/base/teacher";
import { selectRoom } from "@/api/base/room";
import { selectClazz } from "@/api/base/clazz";
import { getToken } from "@/utils/auth";

export default {
  name: "Clazz",
  dicts: ["year_type"],
  data() {
    return {
      isClassDisabled:true, //班级disabled
      classList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级表格数据
      studentList: [],
      //  班级详情
      studentInfo: [],
      stuId: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //起始年
      yearList: [],
      // 专业表格数据
      specialtyList: [],
      // 用户数据
      teacherList: [],
      // 教室数据
      roomList: [],
      // 状态字典
      statusOptions: [],
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/base/clazz/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classId:''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        schoolCode: [{ required: true, message: "不能为空", trigger: "blur" }],
        year: [{ required: true, message: "年级不能为空", trigger: "blur" }],
        title: [
          { required: true, message: "班级名称不能为空", trigger: "blur" },
        ],
        // banpeiUser: [
        //   { required: true, message: "副班不能为空", trigger: "blur" }
        // ],
        // nurseryUser: [
        //   { required: true, message: "保育员不能为空", trigger: "blur" }
        // ],
        // roomId:[
        //   { required: true, message: "固定教室不能为空", trigger: "blur" }
        // ]
      },
      openInfo: false,
      infoParams: {}

    };
  },
  created() {
    this.getList();
    this.getDicts("common_status").then((response) => {
      this.statusOptions = response.data;
    });
    // this.getConfigKey("sys.time.start").then(response => {
    //   var st = parseInt(response.msg);
    //   var dt = new Date();
    //   while(st<=dt.getFullYear()+1){
    //     this.yearList.push({value: st,label: st});
    //     st ++;
    //   }
    // });
    this.getTeacher();
    this.getRoom();
  },
  methods: {
        /**班级*/
        async getqueryFormclassList(){
      this.isClassDisabled = true
      this.queryParams.classId = null
      try {
        let params={}
        if(this.queryParams.year) params.year = this.queryParams.year;
        const {rows}=await selectClazz(params);
        if(rows.length && this.queryParams.year){
          this.isClassDisabled =  false
        }
        this.classList=rows.map(item=>{
          return {
            id:item.id,
            label:item.title,
          }
        })

      }catch (e) {
        console.log(e)
      }
    },
    /**房间**/
    async getRoom() {
      try {
        const { rows } = await selectRoom({ status: "1", type: "1" });
        this.roomList = rows;
      } catch (e) {
        console.log(e);
      }
    },
    /**教师**/
    async getTeacher() {
      try {
        const { rows } = await selectTeacher();
        this.teacherList = rows;
      } catch (e) {
        console.log(e);
      }
    },
    /** 查询班级列表 */
    getList() {
      this.loading = true;
      listStudent(this.queryParams).then((response) => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 查询疫苗详情
    getListInfo() {
      this.loading = true;
      vaccinationRecordList({ stuId: this.stuId }).then((response) => {
        this.studentInfo = response.rows;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleInfo(row) {
        this.openInfo = true
        this.infoParams = row
        this.infoParams.checkVaccinationDetail = []
        this.infoParams.vaccinationDetail.forEach(item => {
            if(item.status == '1') {
                this.infoParams.checkVaccinationDetail.push(item.vacCount)
            }
        })

        // checkVaccinationDetail
    },
    handleChecked(val) {
        console.log(val)
        if(this.infoParams.vaccinationDetail[val].status == '0') {
            this.infoParams.vaccinationDetail[val].status = '1'
        } else if(this.infoParams.vaccinationDetail[val].status == '1') {
            this.infoParams.vaccinationDetail[val].status = '0'
        }
    },
    submitFormInfo() {
        let itemObject = []
        this.infoParams.vaccinationDetail.forEach(element => {
            if(element.status == '1') {
                itemObject.push({
                    vaccinationId: this.infoParams.vaccinationId,
                    stuId: this.stuId,
                    vacCount: element.vacCount,
                    status: element.status
                })
            }
        });
        // todo ,更新接口
        batchUpdate(itemObject).then(res => {
            if(res.code == 200) {
                this.$message.info('修改成功')
                this.openInfo = false
                this.getListInfo()
            }
        })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        specId: null,
        year: null,
        code: null,
        period: 3,
        title: null,
        startDate: null,
        endDate: null,
        roomId: null,
        status: "1",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.isClassDisabled = true
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班级";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
        this.stuId = row.id
        this.open = true;
        this.title = "查看疫苗详情";
        this.getListInfo()
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateClazz(this.form).then((response) => {
              if (response.code == 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addClazz(this.form).then((response) => {
              if (response.code == 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有班级数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportClazz(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "行政班导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
  <style lang="scss" scoped>
.el-dialog__body .el-select,
.el-dialog__body .el-date-editor {
  width: 100%;
}
</style>
